/**
 * Created by x on 17-7-18.
 */
angular.module('tribalc').controller(
    'addApartmentController', ['$scope', '$rootScope', 'Enum', 'ElePosition', 'EleStyle', 'Api', 'ApartmentInfoModel', 'Alert', '$state',
        function ($scope, $rootScope, Enum, ElePosition, EleStyle, Api, ApartmentInfoModel, Alert, $state) {
            init();
            $scope.upload = {pictures: []};
            $scope.submitAddApartinfo = submitAddApartinfo;
            $scope.setupCommunity = setupCommunity;
            $scope.setupProvince = setupProvince;
            $scope.setupCity = setupCity;
            $scope.setupDistrict = setupDistrict;
            $scope.additionalApartInfo = new ApartmentInfoModel();

            $scope.subwayLine = '';
            $scope.subwayStation = '';
            $scope.buildFloor = '';
            $scope.communityName = "";

            setcitys();
            getCommunityList();

            function getCommunityList() {
                Api.getCommunityList(function (result) {
                    $scope.communityList = result.data;
                })
            }

            function getComunityIdUrl() {
                return 'communitys/' + $rootScope.RootCompanyInfo.communityId;
            }

            function init() {
                $scope.uploadApartmentPictures = uploadApartmentPictures

            }

            var uploadNumber = 0;

            function submitAddApartinfo(apartinfomation) {
                // console.log(apartinfomation)
                if ($scope.subwayLine && $scope.subwayStation){
                    apartinfomation.subway = $scope.subwayLine + "/" + $scope.subwayStation;
                }
                apartinfomation.pictures = $scope.upload.pictures;
                if ($scope.buildFloor.indexOf('/') >= 0 && $scope.buildFloor.split('/').length === 2) {
                    apartinfomation.floor = parseInt($scope.buildFloor.split("/")[0]);
                    apartinfomation.buildingHeight = parseInt(($scope.buildFloor.split("/")[1].split("层"))[0]);
                } else {
                    return Alert.alertBox('请检查楼层格式')
                }
                var facilitiesListinfo = getfaciliyiesInfo();
                getFacilities(facilitiesListinfo);
                apartinfomation.facilities = facilitiesListinfo.facilities;

                var tagsListinfo = gettagsInfo();
                getTags(tagsListinfo);
                apartinfomation.tags = tagsListinfo.tags;

                var id = $rootScope.RootCompanyInfo.id;
                var apartmentInfo = new ApartmentInfoModel(apartinfomation);

                if (!checkInformation(apartmentInfo)) {

                    Alert.alertBox("请把信息填写完整");
                }
                else {
                    if (checkTypeOfInformation(apartmentInfo))
                    {
                        Api.addApartmentInfo(apartmentInfo, id, function (result) {
                            // console.log(result)
                            Alert.alertBox('房源提交成功！',function () {
                                $state.go('company.companyApartmentManage');
                            });
                        });
                    }
                }
            }
            function checkTypeOfInformation(apartmentInfo)
            {
                var status = true;
                var require_keys = ['address', 'area', 'around', 'cityId',
                    'communityId', 'disId', 'floor', 'name', 'price', 'provinceId', 'subway',
                    'subwayDistance', 'traffic', 'type','buildingName','buildingId'];
                // var unrequire_keys = ["buildingHeight","facilities","pictures","tags"];//['number','object','object','object']
                var require_types = ['string','number','string','string','string','string','number','string','number',
                    'string','string','string','string','string','string','string'];
                var data = {address:"房源地址", area:'房源面积', around:'房源周边', buildingHeight:'房源楼层',
                    cityId:'房源所在地', communityId:'社区', disId:'房源所在地', facilities:'房源配置', floor:'房源楼层',
                    name:'房源名称', pictures:'房源图片', price:'房源价格', provinceId:'房源所在地', subway:'周边地铁',
                    subwayDistance:'交通距离', tags:'房源标签', traffic:'房源交通', type:'房源户型',
                    buildingName:'楼栋名称',buildingId:'楼栋编号'};
                for (var i = 0; i < require_keys.length; i++)
                {
                    if (typeof (apartmentInfo[require_keys[i]]) != require_types[i] ||
                        require_types[i] == 'number'? isNaN(apartmentInfo[require_keys[i]]) : false)
                    {
                        Alert.alertBox(data[require_keys[i]]+"格式不正确");
                        status = false;
                        break
                    }
                }
                return status;
            }
            function checkInformation(apartmentInfo) {
                var status = true;
                var keys = ['name','price','area','communityId','address','subway','subwayDistance','type',
                    'floor','around','traffic', 'disId','provinceId','cityId','buildingName','buildingId'];
                for (var i = 0; i < keys.length; i++) {
                    if(apartmentInfo[keys[i]] == null){
                        // console.log(keys[i]);
                        status = false;
                        break
                    }
                }
                return status
            }

            function addPicturesInformation() {
                var info = {
                    pictures: $scope.upload.pictures
                };
                return info;
            }

            function getfaciliyiesInfo() {
                var info = {
                    facilities: []
                };
                return info;
            }

            function gettagsInfo() {
                var info = {
                    tags: []
                };
                return info;
            }


            function uploadApartmentPictures(ele) {
                var $divEle = $(ele).parent();
                // console.log($divEle)
                var file = ele.files[0];
                var comunityIdUrl = getComunityIdUrl()
                var index = $(".pro-write-picture-content .pro-write-pictures").index($($divEle).parent());
                // console.log(index)
                setupPictures($($divEle), file);
                // uploadNumber++;
                uploadPicture(file, comunityIdUrl, function (imgeUrl) {
                    $scope.$apply(function () {
                        // console.log(imgeUrl);
                        $scope.upload.pictures[index] = imgeUrl;
                    });
                });
            }

            function uploadPicture(file, comunityIdUrl, sucFuc) {
                Api.uploadPicture(hex_md5(file), comunityIdUrl, function (result) {
                    // console.log(result)
                    Api.callAliyunPicture(result.data.objectKey, result.data.url, file, function (result) {
                        // console.log(result)
                        sucFuc(result);
                    }, function () {
                        uploadNumber--
                    });
                }, function () {
                    uploadNumber--

                });
            }

            function setupPictures($divEle, file) {
                var fileReader = new FileReader();
                fileReader.onload = function () {
                    var imgSrc = fileReader.result;
                    if (imgSrc) {
                        $divEle.find('img').attr("src", imgSrc);
                        $divEle.addClass("pro-logo-completed");

                    }
                };

                fileReader.readAsDataURL(file);
            }


            $scope.apartInfoModel = {};
            function setcitys() {
                Api.getChinaCitysJson(function (result) {
                    $scope.citys = result;
                });
            }

            function setupCommunity(community) {
                $scope.additionalApartInfo.communityId = community.id;
                $scope.communityName = community.name;

            }

            function setupProvince(province) {
                // console.log(province)
                $scope.citysModel = province.city;
                $scope.additionalApartInfo.provinceId = province.provinceId;
            }

            function setupCity(city) {
                $scope.additionalApartInfo.cityId = city.cityId;
                $scope.districtModel = city.district;
            }

            function setupDistrict(district) {
                $scope.additionalApartInfo.disId = district.districtId;
            }

            $scope.to_left_image_container = function () {
                $('#imageContainer').removeClass('pro-write-picture-right');
            }
            $scope.to_right_image_container = function () {
                $('#imageContainer').addClass('pro-write-picture-right');
            };

            function formatPicturePath(apartpic) {

                // var pictures=[];
                // var aliyu="https://buluo-gs-pictures.oss-cn-beijing.aliyuncs.com/";
                // if (apartpic.pictures){
                //     for (var i=0;i<apartpic.pictures.length;i++){
                //
                //         if(apartpic.pictures[i].indexOf(aliyu) !== -1){
                //             apartpic.pictures[i]="oss://" + apartpic.pictures[i].split(aliyu)[1];
                //             console.log(apartpic.pictures[i])
                //
                //         }
                //         pictures.push(apartpic.pictures[i]);
                //     }
                //
                //     return apartpic.pictures=pictures;
                // }
                // return apartpic;
            }

            bindClickEventToFacilitiesTag();
            function bindClickEventToFacilitiesTag() {
                var facilitie = [];
                $('#facilities>div>div').click(function () {
                    if ($(this).hasClass('active')) {
                        facilitie.splice(facilitie.indexOf($(this).text()), 1);
                        $rootScope.facilitiesinfo = facilitie;
                        $(this).removeClass('active');
                    }
                    else {
                        facilitie.push($(this).text());
                        $rootScope.facilitiesinfo = facilitie;
                        $(this).addClass('active');
                    }
                });
            }

            function getFacilities(apartfacilities) {
                apartfacilities.facilities = $rootScope.facilitiesinfo;
                return apartfacilities;
            }


            bindClickEventToTag()
            function bindClickEventToTag() {
                var facilitie = []
                $('#tagsInfo>div>span').click(function () {
                    if ($(this).hasClass('active')) {
                        facilitie.splice(facilitie.indexOf($(this).text()), 1);
                        tagsInfo.facilitiesinfo = facilitie;
                        $(this).removeClass('active');
                    }
                    else {
                        facilitie.push($(this).text());
                        $rootScope.tagsInfo = facilitie;
                        $(this).addClass('active');
                    }
                });
            }

            function getTags(apartfacilities) {
                apartfacilities.tags = $rootScope.tagsInfo;
                // console.log(apartfacilities.tags)
                return apartfacilities;
            }




        }]
);
